package com.qf.give_a_like.service.impl;

import com.google.common.base.Joiner;
import com.qf.give_a_like.domain.User;
import com.qf.give_a_like.mapper.UserMapper;
import com.qf.give_a_like.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements com.qf.give_a_like.service.UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class,readOnly = true,propagation = Propagation.SUPPORTS)
    public User login(String name, String password) {
        User user = userMapper.selectByName(name);
        if (Objects.nonNull(user)){
            if (Objects.equals(user.getPassword(),password)){
                return user;
            }
        }
        return null;
    }

    @Override
    public User likeCard(Integer userId, Integer cardId, Boolean like) {
        User user = userMapper.selectByPrimaryKey(userId);
        String likedIds = user.getLiked();
        if (like){
                    //喜欢那个将追加
            likedIds =  StringUtils.isEmpty(likedIds) ? cardId.toString() : likedIds + "," + cardId;
        }else {

            List<String> likedIdList = Arrays.stream(likedIds.split(",")).collect(Collectors.toList());
            likedIdList.remove(cardId.toString());
            likedIds = Joiner.on(",").join(likedIdList);
        }
        user.setLiked(likedIds);
        userMapper.updateByPrimaryKeySelective(user);

        return user;
    }
}
